package com.etoak.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.etoak.common.core.enums.OrderStateEnum;
import com.etoak.common.core.vo.PageVO;
import com.etoak.common.web.context.LoginContext;
import com.etoak.common.web.exception.CustomException;
import com.etoak.config.OrderQueueConfig;
import com.etoak.entity.Order;
import com.etoak.entity.OrderItem;
import com.etoak.entity.dto.OrderDTO;
import com.etoak.entity.vo.OrderVO;
import com.etoak.mapper.OrderMapper;
import com.etoak.request.OrderRequest;
import com.etoak.service.OrderItemService;
import com.etoak.service.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author et2406
 * @since 2024-11-22
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {


    @Autowired
    OrderItemService orderItemService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void create(OrderDTO orderDto) {

        // 订单id twitter雪花算法
        String orderNo = IdUtil.getSnowflakeNextIdStr();
        Order order = new Order();
        order.setOrderNo(orderNo);
        order.setUserId(Integer.valueOf(LoginContext.getUserId()));
        order.setOrderState(Integer.valueOf(OrderStateEnum.NEW.getState()));
        order.setCreateTime(DateUtil.now());
        order.setPrepareTime(orderDto.getPrepareTime());

        this.save(order);

        List<OrderItem> list = orderDto.getItemList().stream().peek(item -> item.setOrderNo(orderNo))
                .toList();

        orderItemService.saveBatch(list);

        // 发送罅隙到延迟交换机
        rabbitTemplate.convertAndSend(OrderQueueConfig.EXCHANGE,
                OrderQueueConfig.KEY,
                orderNo,
                message -> {
                    message.getMessageProperties().setDelayLong(10000L);
                    return message;
                });
    }

    @Override
    public PageVO<OrderVO> getOrderList(int pageNum, int pageSize, Order order) {
        String userId = LoginContext.getUserId();

        PageHelper.startPage(pageNum,pageSize);
        List<OrderVO> orderList = baseMapper.getOrderList(order,userId);
        PageInfo<OrderVO> pageInfo = new PageInfo<>(orderList);
        return new PageVO<>(pageNum,pageSize,orderList,pageInfo.getTotal());
    }



    @Override
    public void addOrder(OrderRequest orderRequest) {

        if(ObjectUtil.isEmpty(orderRequest.getOrderItemList())){
            throw new CustomException("请填写菜品再进行下单操作");

        }
        // 菜品数量是否够
        ifDishEnough(orderRequest.getOrderItemList());
        // 创建订单
        Order newOrder = new Order();
        newOrder.setCreateTime(DateUtil.now());
        newOrder.setUserId(6);
        String orderNo = IdUtil.randomUUID();
        newOrder.setOrderNo(orderNo);
        newOrder.setOrderState(1);
        newOrder.setPrepareTime(orderRequest.getPrepareTime());
        baseMapper.insert(newOrder);

        // 创建订单详情
        orderItemService.addOrderitemWithOrderNo(newOrder.getOrderNo(),
                orderRequest.getOrderItemList());
    }

    @Override
    public void deleteOrderById(String orderNo) {

        // 先删除对应的item
        orderItemService.remove(new QueryWrapper<OrderItem>().eq("order_no",orderNo));
        // 再删除order
        remove(new QueryWrapper<Order>().eq("order_no",orderNo));
    }

    private void ifDishEnough(List<OrderItem> orderItemList) {

        // 远程调用是否存在

    }
}
